import db from "../models/index.js";
import {Sequelize} from "sequelize";
import dataConfig from "../config/dataConfig.js";

let captcha = db.captcha;
let captchaDao = {};
const captchaLimit = dataConfig.captchaLimit;
const Op = Sequelize.Op;
//判断是否存在这个用户
captchaDao.isExisted = (_account) => {
    return captcha.findOne({
        where: {
            _account
        },
        raw: true,
    });
};

//判断用户是存在且验证码正确
captchaDao.isExistedByCode = (_account, _code) => {
    let now = new Date().getTime();
    return captcha.findOne({
        where: {
            _account,
            _code,
            _timestamp:{
                [Op.gte]:now - captchaLimit
            }
        },
        raw: true,
    });
};
//更新
captchaDao.updateCode = async (_account, _code, _timestamp, t) => {
    if(!t) {
        if(!captchaDao.isExisted(_account)) {
            return captcha.create({_account, _code, _timestamp:new Date().getTime(), raw: true,});
        } else {
            return captcha.update({
                _code,
                _timestamp:_timestamp || new Date().getTime()
            }, {
                where:{
                    _account
                }
            });
        }
    }
    if(!captchaDao.isExisted(_account)) {
        return captcha.create({_account, _code, _timestamp:new Date().getTime()}, {transaction:t});
    } else {
        return captcha.update({
            _code,
            _timestamp:_timestamp || new Date().getTime()
        }, {
            where:{
                _account
            },
            transaction:t
        });
    }
};
//判断用户的发送验证码间隔是否在限制时间内
captchaDao.checkSendCode = (_account) => {
    let now = new Date().getTime();
    return captcha.findOne({
        where: {
            _account,
            _timestamp:{
                [Op.gte]:now - captchaLimit
            }
        },
        raw: true,
    });
};
export default captchaDao;
